package cn.ynrcb.personnelfile.common.utils;

import cn.ynrcb.personnelfile.admin.entity.SmsLogEntity;
import cn.ynrcb.personnelfile.common.exception.MyException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 漫道短信平台
 * 短信发送接口
 *
 * @author swb
 * @version created at 2019年12月4日 上午10:36:28
 */
@Slf4j
public class SmsSendClient {
    private static final String serviceURL = "http://sdk.entinfo.cn:8061/webservice.asmx";
    private String sn = "DXX-WSS-10V-10552";
    private String password = "7q8dt2";
    private String pwd = "";
    private String signature = "【昆明主播查询系统】";  //短信签名，如【盘龙区人民政府网站】
    private String ext = "";


    public SmsSendClient() {this.pwd = getMD5(sn + password);}

    /**
     * 密码 = md5(password + extno + content + mobile)
     *
     * @return
     * @throws IOException
     * @author suj
     * @version created at 2017年5月24日 下午2:48:00
     */
    public String getMD5(String sourceStr) {
        String resultStr = "";
        try {
            byte[] temp = sourceStr.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(temp);
            // resultStr = new String(md5.digest());
            byte[] b = md5.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                        '9', 'A', 'B', 'C', 'D', 'E', 'F'};
                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4) & 0X0F];
                ob[1] = digit[b[i] & 0X0F];
                resultStr += new String(ob);
            }
            return resultStr;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new MyException("短信发送-MD5加密异常！");
        }
    }


    /**
     * 短信验证码
     * @param smsLog
     * @return
     */
    public String sendSmsCode(SmsLogEntity smsLog) {
        try {
            StringBuilder contentBuf = new StringBuilder(this.signature)
                    .append("您本次的验证码是：").append(smsLog.getCode())
                    .append("。该验证码五分钟内有效，请勿将验证码告知他人。");
            smsLog.setContent(contentBuf.toString());

            String content = URLEncoder.encode(contentBuf.toString(), "utf-8");
            return send(smsLog.getPhone(), content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new MyException("短信发送-内容编译异常！");
        } catch (IOException e) {
            throw new MyException("短信发送-关闭流异常！");
        }
    }

    /**
     * 短信验证码
     * @param smsLog
     * @return
     */
    public String sendMsg(SmsLogEntity smsLog) {
        try {
            StringBuilder contentBuf = new StringBuilder("【昆明主播备案系统】")
                    .append("您本次的验证码是：").append(smsLog.getCode())
                    .append("。该验证码五分钟内有效，请勿将验证码告知他人。");
            smsLog.setContent(contentBuf.toString());

            String content = URLEncoder.encode(contentBuf.toString(), "utf-8");
            return send(smsLog.getPhone(), content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new MyException("短信发送-内容编译异常！");
        } catch (IOException e) {
            throw new MyException("短信发送-关闭流异常！");
        }
    }

    /**
     * 自定义内容
     * @param smsLog
     * @return
     */
    public String sendSms(SmsLogEntity smsLog) {
        try {
            StringBuilder contentBuf = new StringBuilder(this.signature).append(smsLog.getContent());
            smsLog.setContent(contentBuf.toString());
            String content = URLEncoder.encode(contentBuf.toString(), "utf-8");
            return send(smsLog.getPhone(), content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new MyException("短信发送-内容编译异常！");
        } catch (IOException e) {
            throw new MyException("短信发送-关闭流异常！");
        }
    }

    /**
     * 主播备案系统自定义内容
     * @param smsLog
     * @return
     */
    public String sendH5Msg(SmsLogEntity smsLog) {
        try {
            StringBuilder contentBuf = new StringBuilder("【昆明主播备案系统】").append(smsLog.getContent());
            smsLog.setContent(contentBuf.toString());
            String content = URLEncoder.encode(contentBuf.toString(), "utf-8");
            return send(smsLog.getPhone(), content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new MyException("短信发送-内容编译异常！");
        } catch (IOException e) {
            throw new MyException("短信发送-关闭流异常！");
        }
    }

//    /**
//     * 调用第三方API接口发送短信
//     * @param mobile 手机号码，可多个，用“,”分隔，最大500
//     * @param content 发送内容
//     * @return
//     * @throws IOException
//     */
//    public String send(String mobile, String content) throws IOException {
//        log.info("-----------------发送短信--------------->");
////        pwd = SecureUtil.md5(password + extno + content + mobile);
////        log.info("password + extno + content + mobile：" + password + extno + content + mobile);
//        String url = URL +"?action=send" + "&account=" + account + "&password=" + password + "&mobile=" + mobile + "&content=" + content + "&extno=" + extno + "&rt=" + rt;
//        log.info("请求url:" + url);
//        String result = "";
//        try {
//            result = HttpClientUtil.doPost(url);
//            log.info("请求结果：" + result);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        log.info("<-----------------发送短信 END---------------");
//        return result;
//    }
//
//    /**
//     * 调用第三方API接口发送短信（点对点p2p）
//     * @param contents 发送内容，号码内容格式为：Mobile#Content
//     *                  多个号码之间用换行分割如：
//     *                  13800000001#下发内容1
//     *                  13800000002#下发内容2
//     *                  13800000003#下发内容3
//     *                  13800000004#下发内容4
//     * @return
//     * @throws IOException
//     */
//    public String sendP2p(List<String> mobiles, List<String> contents){
//        log.info("-----------------发送短信 p2p--------------->");
//        String mobileContentList = "";
//        for (int i = 0 ;i < mobiles.size(); i++) {
//            mobileContentList = mobileContentList + mobiles.get(i) + "#" + contents.get(i) + "\n";
//        }
////        pwd = SecureUtil.md5(password + extno + content + mobile);
////        log.info("password + extno + content + mobile：" + password + extno + content + mobile);
////        String url = URL +"?action=p2p" + "&account=" + account + "&password=" + password + "&mobileContentList=" + mobileContentList + "&extno=" + extno + "&rt=" + rt;
//        String url = URL;
////        log.info("请求url:" + url);
//        String result = "";
//        Map<String, String> param = new HashMap<>();
//        param.put("action","p2p");
//        param.put("account",account);
//        param.put("password",password);
//        param.put("mobileContentList",mobileContentList);
//        param.put("extno",extno);
//        param.put("rt",rt);
//        log.info("param" + param);
//
////        String json = "{\"action\":\"p2p\",\"account\":\"218001\",\"password\":\"H8ZhJc\",\"mobileContentList\":\"mobileAndContent\",\"extno\":\"10690\",\"rt\":\"json\"}";
////        json = json.replace("mobileAndContent",mobileContentList);
////        log.info("json" + json);
//        try {
//            result = HttpClientUtil.doPost(url,param);
//            log.info("请求结果：" + result);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        log.info("<-----------------发送短信 p2p END---------------");
//        return result;
//    }

    /**
     * http调用webservice方式的SDK 发送短信
     *
     * @param mobile
     * @param content
     * @return
     * @throws IOException
     * @author suj
     * @version created at 2017年5月24日 下午2:49:54
     */
    public String send(String mobile, String content) throws IOException {
        String result = null;
        String soapAction = "http://entinfo.cn/mdsmssend";
        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        xml += "<soap:Body>";
        xml += "<mdsmssend  xmlns=\"http://entinfo.cn/\">";
        xml += "<sn>" + sn + "</sn>";
        xml += "<pwd>" + pwd + "</pwd>";
        xml += "<mobile>" + mobile + "</mobile>";
        xml += "<content>" + content + "</content>";
        xml += "<ext>" + ext + "</ext>";
        xml += "<stime></stime>";
        xml += "<rrid></rrid>";
        xml += "<msgfmt></msgfmt>";
        xml += "</mdsmssend>";
        xml += "</soap:Body>";
        xml += "</soap:Envelope>";

        ByteArrayOutputStream bout = null;
        OutputStream out = null;
        InputStreamReader isr = null;
        BufferedReader in = null;
        URL url;
        try {
            url = new URL(serviceURL);

            URLConnection connection = url.openConnection();
            HttpURLConnection httpconn = (HttpURLConnection) connection;
            bout = new ByteArrayOutputStream();
            bout.write(xml.getBytes());
            byte[] b = bout.toByteArray();
            httpconn.setRequestProperty("Content-Length", String
                    .valueOf(b.length));
            httpconn.setRequestProperty("Content-Type",
                    "text/xml; charset=gb2312");
            httpconn.setRequestProperty("SOAPAction", soapAction);
            httpconn.setRequestMethod("POST");
            httpconn.setDoInput(true);
            httpconn.setDoOutput(true);

            out = httpconn.getOutputStream();
            out.write(b);
            out.close();

            isr = new InputStreamReader(httpconn
                    .getInputStream());
            in = new BufferedReader(isr);
            String inputLine;
            while (null != (inputLine = in.readLine())) {
                Pattern pattern = Pattern.compile("<mdsmssendResult>(.*)</mdsmssendResult>");
                Matcher matcher = pattern.matcher(inputLine);
                while (matcher.find()) {
                    result = matcher.group(1);
                }
            }
            return result;
        } catch (Exception e) {
            throw new MyException("短信发送异常！");
        } finally {
            if (bout != null) {
                bout.close();
            }
            if (out != null) {
                out.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (in != null) {
                in.close();
            }
        }
    }

    public static void main(String[] args) {
//        SmsSendClient sms = new SmsSendClient();
//        String ret = sms.sendSmsCode("15891698244", RandomUtil.randomNumbers(6));
//        Console.log(ret);

    }

}
